# coding : UTF-8
import requests
import time
import random
import socket
import httplib
from bs4 import BeautifulSoup




def getUrl(code,startDate,endDate):
    return "http://fund.fund123.cn/HistoryNV/NetValueHistoryTable.aspx?code=" + code + "&startdate=" + startDate + "&enddate=" + endDate;

def get_content(url,data = None):
    header = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'zh-CN,zh;q=0.8',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
    }
    timeout = random.choice(range(80,180))
    while True:
        try:
            rep = requests.get(url,headers = header,timeout = timeout)
            rep.encoding = 'utf-8'
            break
        except socket.timeout as e:
            print('3:', e)
            time.sleep(random.choice(range(8, 15)))

        except socket.error as e:
            print('4:', e)
            time.sleep(random.choice(range(20, 60)))

        except httplib.BAD_REQUEST as e:
            print('5:', e)
            time.sleep(random.choice(range(30, 80)))

    return rep.text

def get_data(html_text):
    bs = BeautifulSoup(html_text,"html.parser")
    data = bs.find('table',{'id':'tblContent'})
    tr = data.find_all('tr',{'class':'tr'})

    for d in tr:
        _data = d.find_all('td')
        print(' unitValue:' + _data[1].get_text())

    return tr



url = getUrl("002132","2016-01-01","2017-12-15")
text = get_content(url)
data = get_data(text)
